package com.eight.cloud.springmvc.utils.thread;

import com.alibaba.ttl.threadpool.TtlExecutors;
import jodd.util.concurrent.ThreadFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import javax.annotation.Resource;
import java.util.concurrent.*;

/**
 * 线程池工具类
 *
 * @ClassName: ThreadPoolUtils
 * @Author: TXC
 * @Date: 2024-10-15 10:40
 **/
@Configuration
public class ThreadPoolConfig {
    @Resource
    private ThreadPoolProperties threadPoolProperties;

    @Bean
    @Primary
    public Executor threadPoolTaskExecutor() {
        ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor();
        threadPoolTaskExecutor.setCorePoolSize(threadPoolProperties.getCorePoolSize());
        threadPoolTaskExecutor.setMaxPoolSize(threadPoolProperties.getMaxPoolSize());
        threadPoolTaskExecutor.setQueueCapacity(threadPoolProperties.getQueueCapacity());
        threadPoolTaskExecutor.setKeepAliveSeconds(threadPoolProperties.getKeepAliveSeconds());
        threadPoolTaskExecutor.setThreadFactory(new ThreadFactoryBuilder().setNameFormat(threadPoolProperties.getPoolName() + "-%d").get());
        threadPoolTaskExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.AbortPolicy() {
            @Override
            public void rejectedExecution(Runnable r, ThreadPoolExecutor e) {
                throw new RejectedExecutionException("线程池已满, 请稍后重试");
            }
        });
        // 初始化线程池
        threadPoolTaskExecutor.initialize();
        return threadPoolTaskExecutor;
    }


    /**
     * 提供线程之间用户信息传递上下文
     * @return 线程池
     */
    @Bean
    public Executor ttlExecutor() {
        return TtlExecutors.getTtlExecutor(threadPoolTaskExecutor());
    }

    @Bean
    public Executor taskExecutor() {
        return ttlExecutor();
    }
}
